package com.itheima.reggie.controller;

import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Employee;
import com.itheima.reggie.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController //RsponseBody + Controller
public class EmployeeController {
	
	@Autowired
	private EmployeeService employeeService;
	
	@Autowired
	private HttpSession session;
	
	
	@PostMapping("/employee/login")
	public ResultInfo login(@RequestBody Map<String, String> map) {
		//接受请求参数
		String username = map.get("username");
		String password = map.get("password");
		
		
		//用户名查询数据库
		ResultInfo userInfo = employeeService.login(username, password);
		
		//将密码与数据库查询结果比对 这是service业务层任务
		
		//如果成功则将用户信息存入session中
		Employee employee = (Employee) userInfo.getData();
		session.setAttribute("SESSION_EMPLOYEE", employee);
		
		//返回本次的查询结果
		
		return userInfo;
	}
	
	//登出
	@PostMapping("/employee/logout")
	public ResultInfo logout() {
		session.invalidate();//只会清除当前用户的session,其他用户的sessi并不会受到影响
		
		
		return ResultInfo.success(null);
	}
	
	//获取员工列表
	@GetMapping("/employee/find")
	public ResultInfo getEmployeeList(String name) {
		return ResultInfo.success(employeeService.findByName(name));
	}
	
	//保存员工
	@PostMapping("/employee")
	public ResultInfo save(@RequestBody Employee employee) {
		employeeService.save(employee);
		return ResultInfo.success("OK");
	}

//	根基id获取员工信息
	@GetMapping("/employee/{id}")
	public ResultInfo findById(@PathVariable("id") String id) {
		
		return ResultInfo.success(employeeService.findById(id));
	}
//修改员工信息
	@PutMapping("/employee")
	public ResultInfo update(@RequestBody Employee employee) {
		employeeService.update(employee);
		return ResultInfo.success("OK");
	}
}
